package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import io.swagger.v3.core.util.Json;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /*
    * 封装参数校验异常
    * */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleIllegalArgumentException(MethodArgumentNotValidException ex){
        String data =ex.getFieldError().getDefaultMessage();
        log.error("doHandleIllegalArgumentException"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    /*
    * 非封装参数校验异常
    * */
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("doHandleConstraintViolationException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    /*
    * 文件上传异常*/
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JsonResult dohandlerMaxUploadSizeExceededException(MaxUploadSizeExceededException e){
        String data="文件上传大小异常，单个文件不能超过100MB";
        log.error("dohandlerMaxUploadSizeExceededException:"+data);
        return new JsonResult(StatusCode.MAX_UPLOAD_SIZE_ERROR,data);
    }
    /*

    * 父类异常处理方法
    * */

//    @ExceptionHandler(RuntimeException.class)
//    public JsonResult doHandleRuntimeException(RuntimeException ex){
//        String data = ex.getMessage();
//        log.error("doHandleRuntimeException:"+data);
//        return new JsonResult(StatusCode.OPERATION_FAILED,data);
//    }
//    @ExceptionHandler(Throwable.class)
//    public JsonResult doHandleThrowable(Throwable ex){
//        String data = ex.getMessage();
//        log.error("doHandleThrowable:"+data);
//        return JsonResult.fail(StatusCode.THROWABLE_ERROR);
//    }
}
